<?php
namespace app\admin\controller;

use \think\Cookie;
use think\Exception;
use think\Db;
use app\admin\controller\Product as ProductController;
use app\admin\model\Product as ProductModel;
use app\admin\model\Pschedule as pscheduleModel;
use app\admin\model\Pactive as pactiveModel;
use app\api\controller\KbxOther;
use app\api\controller\KbxToken;
use app\api\controller\Poi;
use app\api\model\Poi as PModel;
use app\api\controller\ExportExcel;
use app\api\controller\Common;


class Ticket extends User
{

    //产品列表
    public function index()
    {
        $post = $this->request->post();

        $exportFlag = request()->param('exportFlag');//是否为导出

        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page) || isset($exportFlag)){
            //条件从缓存取出
            $post=Cookie::get('productlist');
        }else{
            //把条件写入缓存
            Cookie::set('productlist',$post);
        }

        $nowtime = time();
        $where = [];
        if (isset($post['tripname']) and !empty($post['tripname'])) {
            $where['p.name|p.id|p.item_num'] = ['like', '%' . trim($post['tripname']) . '%'];
        }
        if (isset($post['days']) and !empty($post['days'])) {
            $where['p.days'] = $post['days'];
        }
        if (isset($post['group_type']) and !empty($post['group_type'])) {
            $where['p.group_type'] = $post['group_type'];
        }
        if (isset($post['supplier_id']) and !empty($post['supplier_id'])) {
            $where['p.supplier_id'] = $post['supplier_id'];
        }
        if (isset($post['service_type']) and $post['service_type']!=='') {
            $where['p.service_type'] = $post['service_type'];
        }
        if (isset($post['start_city']) and !empty($post['start_city'])) {
            $where['p.start_city'] = $post['start_city'];
        }
        if (isset($post['service_status']) and $post['service_status']!=='') {
            if($post['service_status']==1){//售卖中
                $where['p.sale_starttime'] = ['LT',$nowtime];
                $where['p.sale_endtime'] = ['GT',$nowtime];
            }elseif($post['service_status']==2){//预售中
                $where['p.sale_starttime'] = ['GT',$nowtime];
            }else{//已下架
                $where['p.sale_endtime'] = ['LT',$nowtime];
            }
        }
        if (isset($post['service_language']) and $post['service_language']!=='') {
            $where['p.service_language'] = $post['service_language'];
        }
        if (!empty($post['supplierItemCode']) && $post['supplierItemCode']!=='') {
            $where['p.supplier_item_code'] = ['like', '%' . trim($post['supplierItemCode']) . '%'];
        }

        //tob是否上架
        if (isset($post['isTob']) && $post['isTob']!==''){
            if($post['isTob']==1){
                $where['s.show_toB'] = 1;
            }elseif($post['isTob']==2){
                $exp =new \think\db\Expression('is null or s.show_toB = 0');
                $where['s.show_toB'] = ['exp',$exp];
            }
        }

        $productModel = new ProductModel();

        $search_page = 20;
        //导出查询条件
        if($exportFlag==1){
            $search_page = 10000;
        }

        $where['p.use_type'] = 3;//use_type=3为门票
        $product = $productModel->alias('p')
            ->join('standardtrip st','st.trip_id=p.id','left')
            ->join('standard s','s.id=st.sid','left')
            ->where($where)
            ->field('p.*,s.show_toB,s.id as standard_id,s.page_index')
            ->order('p.update_time desc')
            ->paginate($search_page);

        $cityData=Db::name('city')->where("type","CITY")->field("id,name")->select();
        $adminData=Db::name('admin')->field("id,nickname")->select();
        $adminArr = [];
        $cityArr = [];
        foreach ($adminData as $k=>$v) {
            $adminArr[$v['id']] = $v['nickname'];
        }
        foreach ($cityData as $k=>$v) {
            $cityArr[$v['id']] = $v['name'];
        }

        for($x=0 ; $x<count($product) ; $x++){
            if(!empty($adminArr[$product[$x]['adminid']])){
                $product[$x]['admin']=$adminArr[$product[$x]['adminid']];
            }else{
                $product[$x]['admin']="";
            }
            if(!empty($cityArr[$product[$x]['start_city']])){
                $product[$x]['start_city']=$cityArr[$product[$x]['start_city']];
            }else{
                $product[$x]['start_city']="";
            }
            if(!empty($adminArr[$product[$x]['update_admin']])){
                $product[$x]['update_admin']=$adminArr[$product[$x]['update_admin']];
            }else{
                $product[$x]['update_admin']="";
            }

            $sale_starttime = $product[$x]['sale_starttime'];
            $sale_endtime = $product[$x]['sale_endtime'];
            $service_status = 0;//状态
            if($nowtime>=$sale_starttime && $nowtime<=$sale_endtime){
                $service_status = 1;
            }elseif($sale_starttime>$nowtime){
                $service_status = 2;
            }
            $product[$x]['service_status'] = $service_status;
            //查询是否存在FAQ
            $faq_flag = 0;
            $faq = db("faq")
                ->where("groupid",$product[$x]['id'])
                ->where("typeid",1)
                ->where("deleted",0)
                ->find();
            if(!empty($faq)){
                $faq_flag = 1;
            }

            $product[$x]['faq_flag'] = $faq_flag;
        }
        //供应商   不能放上面，引入类构造方法会过滤html标签
        list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
        $this->assign('supplier',$supplier);
        foreach ($product as $k=>$v) {
            if(!empty($v['supplier_id'])){
                if($v['supplier_id']=='999999'){
                    $product[$k]['supplier_name'] = '自营';
                }elseif($v['supplier_id']=='77777'){
                    $product[$k]['supplier_name'] = '无';
                }elseif($v['supplier_id']=='1000000'){
                    $product[$k]['supplier_name'] = '其他';
                }else{
                    $product[$k]['supplier_name'] = !empty($supplierNameArr[$v['supplier_id']]) ? $supplierNameArr[$v['supplier_id']] : '';
                }
            }else{
                $product[$k]['supplier_name'] = '';
            }
        }
        //服务类型
        $serviceType = db("service_type")->select();
        $this->assign('serviceType',$serviceType);
        $this->assign('product',$product);
        $this->assign('cityData',$cityData);
        $this->assign('wherelist',$post);

        //导出方法
        if($exportFlag==1){
            $dataArr = array();
            $ExportExcel = new ExportExcel();
            foreach ($product as $k=>$v) {
                $data = array();
                $data['id'] = $v['id'];
                $data['name'] = $v['name'];
                $data['item_num'] = $v['item_num'];
                $data['supplier_name'] = !empty($v['supplier_name']) ? $v['supplier_name'] : '';
                $data['supplier_item_code'] = !empty($v['supplier_item_code']) ? $v['supplier_item_code'] : '';
                $data['days'] = $v['days'];
                $data['start_city'] = $v['start_city'];
                if($v['service_status']==1){
                    $data['service_status'] = "售卖中";
                }elseif($v['service_status']==2){
                    $data['service_status'] = "预售中";
                }else{
                    $data['service_status'] = "已下架";
                }

                if(!empty($v['show_toB']) && $v['show_toB']==1){
                    $data['show_toB'] = "已上架";
                }else{
                    $data['show_toB'] = "已上架";
                }

                $dataArr[] = $data;
            }

            $table_head = array("产品ID","产品名称","产品code","供应商","供应商产品号","天数","出发城市","售卖状态","toB上架");
            $ExportExcel->exportExcel($dataArr, $table_head, "产品列表");
        }else{
            return $this->fetch();
        }
    }

    //提交信息创建产品
    public function info(){
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();
            $adminid = Cookie::get('admin');
            $post['adminid'] = $adminid;
            $post['use_type'] = 3;
            $post['service_type'] = 5;
            $post['update_admin'] = $adminid;
            $post['currency'] = "USD";
            $post['update_time'] = time();
            $post['sale_starttime'] = time();
            $post['sale_endtime'] = time();

            $model = new ProductModel();
            if(false == $model->allowField(true)->save($post)) {
                return $this->error('新增失败');
            } else {
                $productid = $model->getLastInsID();
                $model->allowField(true)->save(['item_num'=>"Ticket".$productid], ['id' => $productid]);
                return $this->success('新增成功',"", $productid);
            }
        } else {
            //供应商   不能放上面，引入类构造方法会过滤html标签
            list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
            $this->assign('supplier',$supplier);

            return $this->fetch();
        }
    }

    //门票产品配置
    public function ticketmake(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new ProductModel();
        $trip = [];
        if($id > 0) {
            $trip = $model->where("id",$id)->find();
            $trip['start_go_time'] = $trip['start_go_time']>0 ? date("Y-m-d",$trip['start_go_time']) : '';
            $tripid = $id;

            $adminArr = db("admin")->field("id,nickname")->select();
            $adminIdArr = [];
            foreach ($adminArr as $admin_k=>$admin_v) {
                $adminIdArr[$admin_v['id']] = $admin_v['nickname'];
            }
            $trip['sale_starttime'] = $trip['sale_starttime']!=='' ? date("Y-m-d",$trip['sale_starttime']) : '';
            $trip['sale_endtime'] = $trip['sale_endtime']!=='' ? date("Y-m-d",$trip['sale_endtime']) : '';
            $trip['update_admin'] = !empty($trip['update_admin']) ? $adminIdArr[$trip['update_admin']] : '';
        }else{
            $trip['sale_starttime'] = '';
            $trip['sale_endtime'] = '';
            $trip['ticket_rate'] = 1;
            $trip['currency'] = 'USD';
            $tripid = 0;
        }

        //服务类型
        $serviceType = db("service_type")->select();
        $this->assign('serviceType',$serviceType);
        $this->assign('tripid',$tripid);
        $this->assign('trip',$trip);
        $this->assign('kbx_url',config('kbx_url'));

        //供应商   不能放上面，引入类构造方法会过滤html标签
        list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
        $this->assign('supplier',$supplier);

        //售价日历
        $dailyPrice = [];
        if(!empty($trip['sale_starttime']) && !empty($trip['sale_endtime'])){
            $dailyPrice = db("product_dailyprice")->where(["product_id"=>$tripid,'time'=>['between',[$trip['sale_starttime'],$trip['sale_endtime']]]])->order("id asc")->select();
        }
        //按天封装数据
        $dailyPriceData = [];
        if(!empty($dailyPrice)){
            foreach ($dailyPrice as $value){
                $dailyPriceData[$value['time'].",".$value['package_id']][] = $value;
            }
        }
        $this->assign('dailyPriceData',(string)json_encode($dailyPriceData));

        $ProductController = new ProductController();
        $ProductController->getPriceForMake($tripid);
        //展示额外价格
        $extra_cost = $ProductController->getExtraCostByProduct($tripid);
        $this->assign("extra_cost",$extra_cost);

        $exchangeData = db("exchange")->select();
        $exchange = [];
        foreach ($exchangeData as $k=>$v) {
            $exchange[$v['currency_code']] = $v['exchange_rate'];
        }
        //获取国家的汇率和货币单位
        $currencyList = (new Common())->getCurrencyListByCity();
        $exchange_currency_codes = array_column($exchangeData,'currency_code');
        foreach ($currencyList as $curr_k=>$curr_v){
            if(!in_array($curr_v['currency_code'],$exchange_currency_codes)){
                unset($currencyList[$curr_k]);
            }
        }
        $this->assign('currencyList',$currencyList);
        $exchangeNum = 1;
        $currency = '￥';
        $currencyCode = 'CNY';
        $currencyName = '人民币';
        foreach ($currencyList as $currency_value){
            if($trip['currency']==$currency_value['currency_code']){
                $exchangeNum = $exchange[$currency_value['currency_code']]??1;
                $currency = $currency_value['currency_sybmol']??'';
                $currencyCode = $currency_value['currency_code']??'';
                $currencyName = $currency_value['currency_name']??'';
            }
        }

        $this->assign('currency_flag',$currency);
        $this->assign('currencyCode',$currencyCode);
        $this->assign('currencyName',$currencyName);
        $this->assign('exchangeNum',$exchangeNum);

        $specs_type = !empty($trip['specs_type']) ? $trip['specs_type'] : 1;
        $specs_name = $specs_type==1 ? "年龄范围" : "车型";
        $table_name = ['规格名称',$specs_name];
        $package = Db::name('product_package')->where("product_id",$id)->where("status",1)->select();
        if($package){
            foreach($package as $key=>$value){
                $package[$key]['specs'] = [];
                $package_id = $value['id'];

                $specs = Db::name('product_specs')->where("package_id",$package_id)->where("status",1)->select();

                array_push($package[$key]['specs'],$specs);
            }
            $this->assign('package',$package);
        }else{
            $this->assign('package','');
        }
        $this->assign('table_name',$table_name);

        return $this->fetch();
    }

    //ajax查询POI
    public function getpoiByInput(){
        $post = $this->request->post();
        $name = isset($post['input']) ? $post['input'] : '';
        $where['deleted'] = 0;
        if($name!==''){
            $where['name|eng_name'] = ['like','%'.$name.'%'];
        }
        $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name,groupid")->select();
        return $poi;
    }


    //**********************套餐配置***********************************************
    //*****************************************************************************
    //产品套餐规格配置
    public function addPackage(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $product = db("product")->where("id",$id)->field("specs_type")->find();
        $specs_type = $product['specs_type'];
        $specs_name = $specs_type==1 ? "年龄范围" : "车型";
        $table_name = ['规格名称','库存','最低下单数','最小增长数',$specs_name];
        //是新增操作
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post()['data'];
            Db::startTrans(); //启动事务
            try {
                //********************套餐********************
                //将全部套餐status都设置为2
                Db::name('product_package')->where("product_id",$id)->update(['status'=>2]);

                $packageData['product_id'] = $id;
                foreach ($post as $key=>$value){
                    $packageData['name'] = $value['package_name'];
                    $packageData['status'] = 1;
                    if(!empty($value['package_id'])){
                        $packageData['updatetime'] = time();
                        Db::name('product_package')->where("id",$value['package_id'])->update($packageData);

                        //********************规格********************
                        $specsData['package_id'] = $value['package_id'];
                        $specsData['updatetime'] = time();
                        $specsData['status'] = 1;
                        if(!empty($value['specsdata'])){
                            //将全部规格status都设置为2
                            Db::name('product_specs')->where("package_id",$value['package_id'])->update(['status'=>2]);
                            foreach ($value['specsdata'] as $k=>$v){
                                $specsData['name'] = $v['specs_name'];
                                $specsData['num'] = $v['specs_num'];
                                $specsData['minorder_num'] = $v['minorder_num'];
                                $specsData['inc_order_num'] = $v['inc_order_num'];
                                if(isset($v['min_age'])){
                                    $specsData['min_age'] = $v['min_age'];
                                }
                                if(isset($v['max_age'])){
                                    $specsData['max_age'] = $v['max_age'];
                                }
                                if(isset($v['car_type'])){
                                    $specsData['car_type'] = $v['car_type'];
                                }
                                if(!empty($v['specs_id'])){
                                    Db::name('product_specs')->where("id",$v['specs_id'])->update($specsData);
                                }else{
                                    $specsData['creattime'] = time();
                                    Db::name('product_specs')->insert($specsData);
                                }
                            }
                        }
                    }else{
                        $packageData['creattime'] = time();
                        $packageData['updatetime'] = time();
                        Db::name('product_package')->insert($packageData);

                        $package_id = Db::name('product_package')->getLastInsID();//规格id
                        $specsData['package_id'] = $package_id;
                        $specsData['creattime'] = time();
                        $specsData['updatetime'] = time();
                        $specsData['status'] = 1;
                        if(!empty($value['specsdata'])){
                            foreach ($value['specsdata'] as $k=>$v){
                                $specsData['name'] = $v['specs_name'];
                                $specsData['num'] = $v['specs_num'];
                                $specsData['minorder_num'] = $v['minorder_num'];
                                $specsData['inc_order_num'] = $v['inc_order_num'];
                                if(isset($v['min_age'])){
                                    $specsData['min_age'] = $v['min_age'];
                                }
                                if(isset($v['max_age'])){
                                    $specsData['max_age'] = $v['max_age'];
                                }
                                if(isset($v['car_type'])){
                                    $specsData['car_type'] = $v['car_type'];
                                }
                                Db::name('product_specs')->insert($specsData);
                            }
                        }
                    }
                }
                Db::commit(); //提交事务

                //删除套餐数据
                $this->delSpecsAndPerson($id);

                return $this->success('提交产品套餐规格成功');
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error('提交产品套餐规格失败');
            }
        }else{
            $package = Db::name('product_package')->where("product_id",$id)->where("status",1)->select();
            if($package){
                foreach($package as $key=>$value){
                    $package[$key]['specs'] = [];
                    $package_id = $value['id'];

                    $specs = Db::name('product_specs')->where("package_id",$package_id)->where("status",1)->select();

                    array_push($package[$key]['specs'],$specs);
                }
                $this->assign('package',$package);
            }else{
                $this->assign('package','');
            }
        }

        $this->assign('id',$id);
        $this->assign('table_name',$table_name);
        $this->assign('specs_type',$specs_type);
        return $this->fetch();
    }
    //删除套餐数据
    protected function delSpecsAndPerson($id)
    {
        $product = db("product")->where("id",$id)->field("id")->find();
        if(!empty($product)){
            $packageIdArr = db("product_package")->where(["product_id"=>$id,"status"=>2])->column("id");
            if(!empty($packageIdArr)){
                DB::startTrans();//开启事务
                try{
                    //直接删除套餐后，规格价格也一并删除
                    db("product_package")->where(["product_id"=>$id,"status"=>2,"id"=>["in",$packageIdArr]])->delete();
                    $specsIdArr = db("product_specs")->where(["package_id"=>["in",$packageIdArr]])->column("id");
                    db("product_specs")->where(["package_id"=>["in",$packageIdArr]])->delete();
                    db("product_dailyprice")->where(["specs_id"=>["in",$specsIdArr]])->delete();
                    //更新价格区间
                    $this->updateProductPriceSection($id);
                    //提交事务
                    DB::commit();
                    return true;
                }catch(\PDOException $e){
                    //回滚事务
                    DB::rollback();
                    return false;
                }
            }
        }
    }
    //ajax删除套餐
    public function delPackage()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $package = db("product_package")->where("id",$post['id'])->find();
            if(empty($package)){
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
            db::startTrans();
            try{
                db("product_package")->delete($post['id']);
                $specsIdArr = db("product_specs")->where("package_id",$post['id'])->column("id");
                db("product_specs")->where("package_id",$post['id'])->delete();
                db("product_dailyprice")->where(["specs_id"=>["in",$specsIdArr]])->delete();
                //更新价格区间
                $this->updateProductPriceSection($package['product_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }
    //ajax删除规格
    public function delSpecs()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $specs = db("product_specs")->where("id",$post['id'])->find();
            if(empty($specs)){
                return json(['code'=>-2,"msg"=>'删除失败']);
            }
            $package = db("product_package")->where("id",$specs['package_id'])->find();
            if(empty($package)){
                return json(['code'=>-3,"msg"=>'删除失败']);
            }
            db::startTrans();
            try{
                db("product_specs")->where("id",$post['id'])->delete();
                db("product_dailyprice")->where("specs_id",$specs['id'])->delete();
                //更新价格区间
                $this->updateProductPriceSection($package['product_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }
    //ajax修改规格类型
    public function changeSpecsType(){
        if($this->request->isPost()) {
            $post = $this->request->post();
            if(empty($post['id'] || $post['specs_type'])){
                return $this->error("请求错误，字段错误");
            }
            $id = $post['id'];
            $specs_type = $post['specs_type'];
            $res = db("product")->where("id",$id)->update(['specs_type'=>$specs_type]);
            if($res!==false){
                return $this->success('更新规格类型成功');
            }else{
                return $this->error('更新失败');
            }
        } else {
            return $this->error('更新失败');
        }
    }


    //ajax修改利率
    public function changeRate(){
        if($this->request->isPost()) {
            $post = $this->request->post();
            if(empty($post['id']) || empty($post['ticket_rate']) || empty($post['currency'])){
                return $this->error("请求错误，字段错误");
            }
            $id = $post['id'];
            $ticket_rate = $post['ticket_rate'];
            $currency = $post['currency'];
            $res = db("product")->where("id",$id)->update(['ticket_rate'=>$ticket_rate,'currency'=>$currency]);
            if($res!==false){
                return $this->success('修改成功');
            }else{
                return $this->error('更新失败');
            }
        } else {
            return $this->error('更新失败');
        }
    }


    //【普通成本】价格配置提交
    public function ajaxsetgoodsprice(){
        $post = request()->post();
        $param = json_decode($post['param'],true);
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $this->addPersonList($param['package_id'],$param['specs'],$param['date']);

            db::commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败'.$e]);
        }
    }
    //写入库表
    protected function addPersonList($package_id,$specs,$date){
        if(empty($specs))return false;
        if(empty($date))return false;
        $package_info = db("product_package")->find($package_id);
        if(empty($package_info))return false;
        $del_res = db("product_dailyprice")
            ->where(['product_id'=>$package_info['product_id'],'time'=>['in',$date]])
            ->delete();
        //删除已有套餐日期价格数据
        if($del_res===false)return false;

        $vehicle_type = 0;
        if($package_info['vehicle_type']!==$vehicle_type) {
            $del_res = db("product_dailyprice")->where(['package_id' => $package_id])->delete();
            //删除失败
            if ($del_res === false) return false;

            db("product_package")
                ->where("id",$package_id)
                ->update([
                    'vehicle_type'=>$vehicle_type,
                    'updatetime'=>time()
                ]);
        }

        foreach ($specs as $key => $value) {
            $insertAll = [];
            $product_specs = db("product_specs")->find($value['id']);
            foreach ($date as $day) {
                $insertAll[] = [
                    'time' => $day,
                    'product_id' => $package_info['product_id'],
                    'package_id' => $package_id,
                    'specs_id' => $value['id'],
                    'name' => $product_specs['name'],
                    'price' => $value['price'],
                    'total_cost' => $value['cost'],
                    'exchange_num' => $value['exchangeNum'],
                    'cost_currency' => $value['currency'],
                    'num' => $product_specs['num'],
                    'minorder_num' => $product_specs['minorder_num'],
                    'inc_order_num' => $product_specs['inc_order_num'],
                ];
            }
            //插入数据
            db("product_dailyprice")->insertAll($insertAll);
            //更新价格区间
            $this->updateProductPriceSection($package_info['product_id']);
        }
    }


    //更新产品最高价&最低价
    public function updateProductPriceSection($product_id)
    {
        $product = db("product")->where("id",$product_id)->find();
        //获取目前商品的最低价和最高价
        $product_stime = date("Y-m-d",$product['sale_starttime']);
        $product_etime = date("Y-m-d",$product['sale_endtime']);
        $price_data = $this->personDayMaxAndMinPrice($product_id,$product_stime,$product_etime);
        if(!empty($price_data) && $price_data['min']<=$price_data['max']){
            $min = $price_data['min'];
            $max = $price_data['max'];
        }else{
            $min = $max = 0;
        }
        $price_section = $min.'~'.$max;
        //更新价格区间
        db('product')->where('id',$product_id)->update(['price_section'=>$price_section,'new_price_flag'=>1]);
    }
    protected function personDayMaxAndMinPrice($product_id,$starttime,$endtime)
    {
        $list = db("product_dailyprice")
            ->where(["product_id"=>$product_id,"time"=>['between',[$starttime,$endtime]]])
            ->field("product_id,price,package_id,specs_id")
            ->select();

        if(empty($list)){
            return false;
        }else{
            $packageList = array_column($list,"package_id");
            if(empty($packageList)){
                return false;
            }else{
                $packageList = array_unique($packageList);
                $package_where['id'] = ["in",$packageList];
                $package_where['status'] = 1;
                $packageData = db("product_package")->where($package_where)->column("id");
                if(empty($packageData)){
                    return false;
                }else{
                    $min = $max = $list[0]['price'];
                    foreach ($list as $key=>$value){
                        if(in_array($value['package_id'],$packageData)){
                            $min = $min < $value['price']?$min:$value['price'];
                            $max = $max > $value['price']?$max:$value['price'];
                        }
                    }
                    return ["min"=>$min,"max"=>$max];
                }
            }
        }
    }





}
